using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Shared.Domain.Photos
{
    /// <summary>
    /// 相册领域实体
    /// 支持多级目录结构，用于组织和管理照片
    /// </summary>
    public class Gallery : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 相册名称
        /// </summary>
        [Required]
        [MaxLength(200)]
        public virtual string Name { get; protected set; }

        /// <summary>
        /// 相册描述
        /// </summary>
        [MaxLength(1000)]
        public virtual string Description { get; protected set; }

        /// <summary>
        /// 父相册ID，支持多级目录结构
        /// </summary>
        public virtual Guid? ParentId { get; protected set; }

        /// <summary>
        /// 相册路径，基于目录结构的完整路径
        /// </summary>
        [MaxLength(1000)]
        public virtual string Path { get; protected set; }

        /// <summary>
        /// 相册层级深度，根目录为0
        /// </summary>
        public virtual int Level { get; protected set; }

        /// <summary>
        /// 排序顺序
        /// </summary>
        public virtual int SortOrder { get; protected set; }

        /// <summary>
        /// 相册封面图片ID
        /// </summary>
        public virtual Guid? CoverImageId { get; protected set; }

        /// <summary>
        /// 相册类型
        /// </summary>
        public virtual GalleryType Type { get; protected set; }

        /// <summary>
        /// 是否为系统相册（不可删除）
        /// </summary>
        public virtual bool IsSystem { get; protected set; }

        /// <summary>
        /// 是否公开访问
        /// </summary>
        public virtual bool IsPublic { get; protected set; }

        /// <summary>
        /// 是否启用密码保护
        /// </summary>
        public virtual bool IsPasswordProtected { get; protected set; }

        /// <summary>
        /// 访问密码
        /// </summary>
        [MaxLength(100)]
        public virtual string Password { get; protected set; }

        /// <summary>
        /// 相册标签
        /// </summary>
        public virtual List<string> Tags { get; protected set; }

        /// <summary>
        /// 相册元数据
        /// </summary>
        public virtual Dictionary<string, object> Metadata { get; protected set; }

        /// <summary>
        /// 相册配置
        /// </summary>
        public virtual GalleryConfiguration Configuration { get; protected set; }

        /// <summary>
        /// 相册统计信息
        /// </summary>
        public virtual GalleryStatistics Statistics { get; protected set; }

        /// <summary>
        /// 相册权限设置
        /// </summary>
        public virtual GalleryPermissionSettings PermissionSettings { get; protected set; }

        /// <summary>
        /// 父相册导航属性
        /// </summary>
        public virtual Gallery Parent { get; protected set; }

        /// <summary>
        /// 子相册集合
        /// </summary>
        public virtual ICollection<Gallery> Children { get; protected set; }

        /// <summary>
        /// 相册照片集合
        /// </summary>
        public virtual ICollection<Photo> Photos { get; protected set; }

        protected Gallery()
        {
            Tags = new List<string>();
            Metadata = new Dictionary<string, object>();
            Configuration = new GalleryConfiguration();
            Statistics = new GalleryStatistics();
            PermissionSettings = new GalleryPermissionSettings();
            Children = new List<Gallery>();
            Photos = new List<Photo>();
        }

        public Gallery(
            Guid id,
            string name,
            string description = null,
            Guid? parentId = null,
            GalleryType type = GalleryType.Custom,
            Guid? tenantId = null) : base(id)
        {
            Name = name;
            Description = description;
            ParentId = parentId;
            Type = type;
            TenantId = tenantId;

            Tags = new List<string>();
            Metadata = new Dictionary<string, object>();
            Configuration = new GalleryConfiguration();
            Statistics = new GalleryStatistics();
            PermissionSettings = new GalleryPermissionSettings();
            Children = new List<Gallery>();
            Photos = new List<Photo>();

            CalculatePathAndLevel();
        }

        /// <summary>
        /// 更新相册基本信息
        /// </summary>
        public virtual void UpdateBasicInfo(string name, string description = null)
        {
            Name = name;
            Description = description;
        }

        /// <summary>
        /// 移动相册到新的父相册
        /// </summary>
        public virtual void MoveTo(Guid? newParentId)
        {
            ParentId = newParentId;
            CalculatePathAndLevel();
        }

        /// <summary>
        /// 设置相册封面
        /// </summary>
        public virtual void SetCoverImage(Guid? coverImageId)
        {
            CoverImageId = coverImageId;
        }

        /// <summary>
        /// 更新相册类型
        /// </summary>
        public virtual void UpdateType(GalleryType type)
        {
            Type = type;
        }

        /// <summary>
        /// 设置公开访问状态
        /// </summary>
        public virtual void SetPublicAccess(bool isPublic)
        {
            IsPublic = isPublic;

            // 如果设置为公开，清除密码保护
            if (isPublic)
            {
                IsPasswordProtected = false;
                Password = null;
            }
        }

        /// <summary>
        /// 设置密码保护
        /// </summary>
        public virtual void SetPasswordProtection(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                IsPasswordProtected = false;
                Password = null;
            }
            else
            {
                IsPasswordProtected = true;
                Password = password;
                IsPublic = false; // 密码保护的相册不能公开
            }
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        public virtual void UpdateTags(List<string> tags)
        {
            Tags = tags ?? new List<string>();
        }

        /// <summary>
        /// 添加标签
        /// </summary>
        public virtual void AddTag(string tag)
        {
            if (!string.IsNullOrWhiteSpace(tag) && !Tags.Contains(tag))
            {
                Tags.Add(tag);
            }
        }

        /// <summary>
        /// 移除标签
        /// </summary>
        public virtual void RemoveTag(string tag)
        {
            Tags.Remove(tag);
        }

        /// <summary>
        /// 更新元数据
        /// </summary>
        public virtual void UpdateMetadata(Dictionary<string, object> metadata)
        {
            Metadata = metadata ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 设置元数据项
        /// </summary>
        public virtual void SetMetadata(string key, object value)
        {
            Metadata[key] = value;
        }

        /// <summary>
        /// 移除元数据项
        /// </summary>
        public virtual void RemoveMetadata(string key)
        {
            Metadata.Remove(key);
        }

        /// <summary>
        /// 更新相册配置
        /// </summary>
        public virtual void UpdateConfiguration(GalleryConfiguration configuration)
        {
            Configuration = configuration ?? new GalleryConfiguration();
        }

        /// <summary>
        /// 更新权限设置
        /// </summary>
        public virtual void UpdatePermissionSettings(GalleryPermissionSettings permissionSettings)
        {
            PermissionSettings = permissionSettings ?? new GalleryPermissionSettings();
        }

        /// <summary>
        /// 增加照片数量
        /// </summary>
        public virtual void IncrementPhotoCount(int count = 1)
        {
            Statistics.TotalPhotos += count;
            Statistics.LastPhotoAddedTime = DateTime.Now;
        }

        /// <summary>
        /// 减少照片数量
        /// </summary>
        public virtual void DecrementPhotoCount(int count = 1)
        {
            Statistics.TotalPhotos = Math.Max(0, Statistics.TotalPhotos - count);
        }

        /// <summary>
        /// 更新相册大小
        /// </summary>
        public virtual void UpdateTotalSize(long sizeDelta)
        {
            Statistics.TotalSize = Math.Max(0, Statistics.TotalSize + sizeDelta);
        }

        /// <summary>
        /// 更新统计信息
        /// </summary>
        public virtual void UpdateStatistics(GalleryStatistics statistics)
        {
            Statistics = statistics ?? new GalleryStatistics();
        }

        /// <summary>
        /// 计算路径和层级
        /// </summary>
        private void CalculatePathAndLevel()
        {
            if (ParentId == null)
            {
                Level = 0;
                Path = Name;
            }
            else
            {
                // 在实际应用中，这里需要查询父相册的路径信息
                // 暂时设置默认值，在服务层进行完整的路径计算
                Level = 1;
                Path = $"{ParentId}/{Name}";
            }
        }

        /// <summary>
        /// 设置完整路径信息（由服务层调用）
        /// </summary>
        public virtual void SetPathInfo(string fullPath, int level)
        {
            Path = fullPath;
            Level = level;
        }

        /// <summary>
        /// 检查是否可以删除
        /// </summary>
        public virtual bool CanDelete()
        {
            return !IsSystem;
        }

        /// <summary>
        /// 检查是否可以添加子相册
        /// </summary>
        public virtual bool CanAddChildGallery()
        {
            return !IsSystem || Type == GalleryType.Custom;
        }

        /// <summary>
        /// 获取所有子相册ID（递归）
        /// </summary>
        public virtual List<Guid> GetAllChildGalleryIds()
        {
            var childIds = new List<Guid>();
            foreach (var child in Children)
            {
                childIds.Add(child.Id);
                childIds.AddRange(child.GetAllChildGalleryIds());
            }
            return childIds;
        }

        /// <summary>
        /// 获取深度（包含所有子级的最大深度）
        /// </summary>
        public virtual int GetDepth()
        {
            if (Children == null || Children.Count == 0)
            {
                return 0;
            }

            int maxChildDepth = 0;
            foreach (var child in Children)
            {
                maxChildDepth = Math.Max(maxChildDepth, child.GetDepth());
            }

            return maxChildDepth + 1;
        }

        /// <summary>
        /// 检查是否为指定相册的祖先
        /// </summary>
        public virtual bool IsAncestorOf(Guid galleryId)
        {
            return GetAllChildGalleryIds().Contains(galleryId);
        }
    }

    /// <summary>
    /// 相册类型枚举
    /// </summary>
    public enum GalleryType
    {
        /// <summary>
        /// 自定义相册
        /// </summary>
        Custom = 0,

        /// <summary>
        /// 系统相册
        /// </summary>
        System = 1,

        /// <summary>
        /// 自动生成相册
        /// </summary>
        AutoGenerated = 2,

        /// <summary>
        /// 时间线相册
        /// </summary>
        Timeline = 3,

        /// <summary>
        /// 地理位置相册
        /// </summary>
        Location = 4,

        /// <summary>
        /// 人物相册
        /// </summary>
        People = 5,

        /// <summary>
        /// 事件相册
        /// </summary>
        Event = 6,

        /// <summary>
        /// 收藏夹
        /// </summary>
        Favorites = 7
    }

    /// <summary>
    /// 相册配置
    /// </summary>
    public class GalleryConfiguration
    {
        /// <summary>
        /// 是否允许子相册
        /// </summary>
        public bool AllowChildren { get; set; } = true;

        /// <summary>
        /// 最大子相册数量
        /// </summary>
        public int MaxChildrenCount { get; set; } = 100;

        /// <summary>
        /// 是否允许直接上传照片
        /// </summary>
        public bool AllowDirectUpload { get; set; } = true;

        /// <summary>
        /// 最大照片数量
        /// </summary>
        public int MaxPhotosCount { get; set; } = 10000;

        /// <summary>
        /// 照片排序方式
        /// </summary>
        public PhotoSortOrder PhotoSortOrder { get; set; } = PhotoSortOrder.ByDateDesc;

        /// <summary>
        /// 默认视图模式
        /// </summary>
        public GalleryViewMode DefaultViewMode { get; set; } = GalleryViewMode.Grid;

        /// <summary>
        /// 网格列数
        /// </summary>
        public int GridColumns { get; set; } = 4;

        /// <summary>
        /// 是否显示照片详情
        /// </summary>
        public bool ShowPhotoDetails { get; set; } = true;

        /// <summary>
        /// 是否启用批量操作
        /// </summary>
        public bool EnableBatchOperations { get; set; } = true;

        /// <summary>
        /// 是否启用搜索
        /// </summary>
        public bool EnableSearch { get; set; } = true;

        /// <summary>
        /// 是否启用标签
        /// </summary>
        public bool EnableTags { get; set; } = true;

        /// <summary>
        /// 是否启用分享
        /// </summary>
        public bool EnableSharing { get; set; } = true;

        /// <summary>
        /// 是否启用下载
        /// </summary>
        public bool EnableDownload { get; set; } = true;

        /// <summary>
        /// 是否启用评论
        /// </summary>
        public bool EnableComments { get; set; } = false;

        /// <summary>
        /// 主题设置
        /// </summary>
        public string Theme { get; set; } = "default";

        /// <summary>
        /// 自定义CSS样式
        /// </summary>
        public string CustomStyles { get; set; }
    }

    /// <summary>
    /// 照片排序方式
    /// </summary>
    public enum PhotoSortOrder
    {
        /// <summary>
        /// 按日期降序
        /// </summary>
        ByDateDesc = 0,

        /// <summary>
        /// 按日期升序
        /// </summary>
        ByDateAsc = 1,

        /// <summary>
        /// 按名称降序
        /// </summary>
        ByNameDesc = 2,

        /// <summary>
        /// 按名称升序
        /// </summary>
        ByNameAsc = 3,

        /// <summary>
        /// 按大小降序
        /// </summary>
        BySizeDesc = 4,

        /// <summary>
        /// 按大小升序
        /// </summary>
        BySizeAsc = 5,

        /// <summary>
        /// 随机排序
        /// </summary>
        Random = 6,

        /// <summary>
        /// 手动排序
        /// </summary>
        Manual = 7
    }

    /// <summary>
    /// 相册视图模式
    /// </summary>
    public enum GalleryViewMode
    {
        /// <summary>
        /// 网格视图
        /// </summary>
        Grid = 0,

        /// <summary>
        /// 列表视图
        /// </summary>
        List = 1,

        /// <summary>
        /// 详细视图
        /// </summary>
        Detail = 2,

        /// <summary>
        /// 幻灯片视图
        /// </summary>
        Slideshow = 3,

        /// <summary>
        /// 时间线视图
        /// </summary>
        Timeline = 4,

        /// <summary>
        /// 地图视图
        /// </summary>
        Map = 5
    }

    /// <summary>
    /// 相册统计信息
    /// </summary>
    public class GalleryStatistics
    {
        /// <summary>
        /// 总照片数量
        /// </summary>
        public int TotalPhotos { get; set; }

        /// <summary>
        /// 总文件大小（字节）
        /// </summary>
        public long TotalSize { get; set; }

        /// <summary>
        /// 最后添加照片时间
        /// </summary>
        public DateTime? LastPhotoAddedTime { get; set; }

        /// <summary>
        /// 最后访问时间
        /// </summary>
        public DateTime? LastAccessTime { get; set; }

        /// <summary>
        /// 访问次数
        /// </summary>
        public int AccessCount { get; set; }

        /// <summary>
        /// 分享次数
        /// </summary>
        public int ShareCount { get; set; }

        /// <summary>
        /// 下载次数
        /// </summary>
        public int DownloadCount { get; set; }

        /// <summary>
        /// 评论数量
        /// </summary>
        public int CommentCount { get; set; }

        /// <summary>
        /// 子相册数量
        /// </summary>
        public int ChildCount { get; set; }

        /// <summary>
        /// 按类型统计的照片数量
        /// </summary>
        public Dictionary<string, int> PhotosByType { get; set; } = new();

        /// <summary>
        /// 按日期统计的照片数量
        /// </summary>
        public Dictionary<string, int> PhotosByDate { get; set; } = new();
    }

    /// <summary>
    /// 相册权限设置
    /// </summary>
    public class GalleryPermissionSettings
    {
        /// <summary>
        /// 访问权限列表
        /// </summary>
        public List<GalleryPermission> AccessPermissions { get; set; } = new();

        /// <summary>
        /// 编辑权限列表
        /// </summary>
        public List<GalleryPermission> EditPermissions { get; set; } = new();

        /// <summary>
        /// 删除权限列表
        /// </summary>
        public List<GalleryPermission> DeletePermissions { get; set; } = new();

        /// <summary>
        /// 分享权限列表
        /// </summary>
        public List<GalleryPermission> SharePermissions { get; set; } = new();

        /// <summary>
        /// 是否继承父相册权限
        /// </summary>
        public bool InheritParentPermissions { get; set; } = true;

        /// <summary>
        /// 权限生效时间
        /// </summary>
        public DateTime? PermissionStartTime { get; set; }

        /// <summary>
        /// 权限过期时间
        /// </summary>
        public DateTime? PermissionEndTime { get; set; }
    }

    /// <summary>
    /// 相册权限
    /// </summary>
    public class GalleryPermission
    {
        /// <summary>
        /// 权限类型
        /// </summary>
        public GalleryPermissionType Type { get; set; }

        /// <summary>
        /// 用户ID或角色ID
        /// </summary>
        public string SubjectId { get; set; }

        /// <summary>
        /// 主体名称
        /// </summary>
        public string SubjectName { get; set; }

        /// <summary>
        /// 是否为角色权限
        /// </summary>
        public bool IsRole { get; set; }

        /// <summary>
        /// 权限级别
        /// </summary>
        public GalleryPermissionLevel Level { get; set; }

        /// <summary>
        /// 授予时间
        /// </summary>
        public DateTime GrantedTime { get; set; } = DateTime.Now;

        /// <summary>
        /// 授予者ID
        /// </summary>
        public string GrantedBy { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime? ExpirationTime { get; set; }
    }

    /// <summary>
    /// 相册权限类型
    /// </summary>
    public enum GalleryPermissionType
    {
        /// <summary>
        /// 访问权限
        /// </summary>
        Access = 0,

        /// <summary>
        /// 编辑权限
        /// </summary>
        Edit = 1,

        /// <summary>
        /// 删除权限
        /// </summary>
        Delete = 2,

        /// <summary>
        /// 分享权限
        /// </summary>
        Share = 3,

        /// <summary>
        /// 管理权限
        /// </summary>
        Manage = 4
    }

    /// <summary>
    /// 相册权限级别
    /// </summary>
    public enum GalleryPermissionLevel
    {
        /// <summary>
        /// 无权限
        /// </summary>
        None = 0,

        /// <summary>
        /// 只读权限
        /// </summary>
        ReadOnly = 1,

        /// <summary>
        /// 读写权限
        /// </summary>
        ReadWrite = 2,

        /// <summary>
        /// 完全控制
        /// </summary>
        FullControl = 3
    }
}